package com.example.takeaway.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.takeaway.converter.AddressConverter;
import com.example.takeaway.mapper.DeliveryAddressMapper;
import com.example.takeaway.model.bo.DeliveryAddress;
import com.example.takeaway.model.dto.AddressDTO;
import com.example.takeaway.model.dto.AddressEditorDTO;
import com.example.takeaway.model.vo.AddressVO;
import com.example.takeaway.service.DeliveryAddressService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 收货地址表 服务实现类
 * </p>
 *
 * @author 邢晨旭
 * @since 2023-10-12
 */
@Service
public class DeliveryAddressServiceImpl extends ServiceImpl<DeliveryAddressMapper, DeliveryAddress> implements DeliveryAddressService {

    @Resource
    AddressConverter converter;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addAddress(AddressDTO addressDTO, Long userId) {
        addressDTO.setUserId(userId);
        DeliveryAddress address = converter.toDeliveryAddress(addressDTO);
        if (address.getIsDefault() == 1) {
            //如果是默认地址，将其他地址设置为非默认
            baseMapper.updateDefault(userId);
        }
        baseMapper.insert(address);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateAddress(AddressEditorDTO addressDTO) {
        DeliveryAddress address = converter.toDeliveryAddress(addressDTO);
        if (address.getIsDefault() == 1) {
            //如果是默认地址，将其他地址设置为非默认
            if (address.getUserId() == null) {
                //todo 从token中获取用户id
                address.setUserId(111L);
            }
            baseMapper.updateDefault(address.getUserId());
        }
        baseMapper.updateById(address);
    }

    @Override
    public void deleteById(Long id) {
        baseMapper.deleteAddressById(id);
    }

    @Override
    public List<AddressVO> queryListByUserId(Long userId) {
        return baseMapper.queryListByUserId(userId);
    }

    @Override
    public AddressVO queryById(Long id) {
        return converter.toAddressVO(baseMapper.selectById(id));
    }
}
